console.log('XHR Interceptor initializing...');

// 保存原始的XMLHttpRequest
const OriginalXHR = window.XMLHttpRequest;

// 需要拦截的URL模式
const INTERCEPT_PATTERNS = [
    'LHECISM/B2CMainPlat_00',
    'LHECISM/B2CMainPlat_GRAY',
    'LHECISM/CCBYXEncryptSerReqServlet_GRAY'
];

// 创建新的构造函数
function XMLHttpRequestWrapper() {
    const xhr = new OriginalXHR();
    const originalOpen = xhr.open;
    const originalSend = xhr.send;

    // 重写open方法
    xhr.open = function(method, url, ...args) {
        // 处理相对路径，转换为完整 URL
        const fullUrl = new URL(url, window.location.href);
        this._requestMethod = method;
        this._requestUrl = fullUrl.href;
        this._requestTime = new Date();
        this._domain = fullUrl.hostname;
        return originalOpen.apply(this, [method, url, ...args]);
    };

    // 获取请求的txcode或生成标识
    function getTxcode(url, requestBody) {
        // 尝试从URL参数获取txcode
        const urlParams = new URL(url).searchParams;
        let txcode = urlParams.get('txcode');
        
        // 如果URL中没有txcode，尝试从请求体获取
        if (!txcode && requestBody && requestBody.TXCODE) {
            txcode = requestBody.TXCODE;
        }
        
        // 如果还是没有txcode，根据URL生成标识
        if (!txcode) {
            const urlPath = new URL(url).pathname;
            if (urlPath.includes('CCBYXEncryptSerReqServlet_GRAY')) {
                txcode = 'ENCRYPT_GRAY';
            } else if (urlPath.includes('B2CMainPlat_GRAY')) {
                txcode = 'B2C_GRAY';
            } else {
                txcode = 'Unknown';
            }
        }
        
        return txcode;
    }

    // 重写send方法
    xhr.send = function(body) {
        // 解析请求体
        let parsedBody = body;
        if (typeof body === 'string') {
            try {
                // 尝试解析 JSON
                parsedBody = JSON.parse(body);
            } catch (e) {
                try {
                    // 尝试解析 URL 编码的表单数据
                    const formData = new URLSearchParams(body);
                    parsedBody = Object.fromEntries(formData.entries());
                } catch (e2) {
                    console.error('Failed to parse request body:', e2);
                }
            }
        }
        this._requestBody = parsedBody;
        
        // 检查是否需要拦截
        const shouldIntercept = INTERCEPT_PATTERNS.some(pattern => 
            this._requestUrl && this._requestUrl.includes(pattern)
        );
        
        if (shouldIntercept) {
            this.addEventListener('readystatechange', function() {
                if (this.readyState === 4) {
                    try {
                        const responseData = JSON.parse(this.responseText);
                        const txcode = getTxcode(this._requestUrl, this._requestBody);

                        // 获取标签页信息，如果不可用则使用默认值
                        const tabInfo = window.__TAB_INFO__ || {
                            id: 'unknown',
                            title: document.title || 'Unknown Tab',
                            url: window.location.href
                        };
                        
                        // 通过 postMessage 发送数据给 content script
                        window.postMessage({
                            type: 'XHR_INTERCEPTOR_DATA',
                            data: {
                                txcode: txcode,
                                url: this._requestUrl,
                                domain: this._domain,
                                method: this._requestMethod,
                                timestamp: this._requestTime.toISOString(),
                                time: this._requestTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
                                status: this.status,
                                requestBody: this._requestBody,
                                responseData: responseData,
                                tabId: tabInfo.id,
                                tabTitle: tabInfo.title,
                                tabUrl: tabInfo.url
                            }
                        }, '*');
                    } catch (e) {
                        console.error('Error processing response:', e);
                    }
                }
            });
        }
        return originalSend.apply(this, arguments);
    };

    return xhr;
}

// 复制原始XMLHttpRequest的属性
XMLHttpRequestWrapper.prototype = OriginalXHR.prototype;
XMLHttpRequestWrapper.DONE = OriginalXHR.DONE;
XMLHttpRequestWrapper.HEADERS_RECEIVED = OriginalXHR.HEADERS_RECEIVED;
XMLHttpRequestWrapper.LOADING = OriginalXHR.LOADING;
XMLHttpRequestWrapper.OPENED = OriginalXHR.OPENED;
XMLHttpRequestWrapper.UNSENT = OriginalXHR.UNSENT;

// 替换全局的XMLHttpRequest
window.XMLHttpRequest = XMLHttpRequestWrapper;

console.log('XHR Interceptor initialized successfully');